package com.example.kabaouser.controller;

import com.example.kabaouser.DTO.KaBaoUserDTO;
import com.example.kabaouser.Utils.AesUtil;
import com.example.kabaouser.Utils.ResultVOUtil;
import com.example.kabaouser.VO.ResultUserInfoVO;
import com.example.kabaouser.VO.ResultVO;
import com.example.kabaouser.enums.ResultEnum;
import com.example.kabaouser.exception.CreditException;
import com.example.kabaouser.form.UserLoginForm;
import com.example.kabaouser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping(value = "/login")
    public ResultVO login(@Valid UserLoginForm userLoginForm,
                          BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            throw new CreditException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        Map<String,String> map = userService.login(userLoginForm);
        return ResultVOUtil.success(map);
    }

    @GetMapping("/info")
    public ResultVO getUserInfo(HttpServletRequest request) {
        String token = AesUtil.decryptData(request.getHeader("Access-User-Token"));
        KaBaoUserDTO kaBaoUserDTO = userService.findDTOByToken(token);
        kaBaoUserDTO.setToken(AesUtil.encryptData(kaBaoUserDTO.getToken()));
        ResultUserInfoVO resultUserInfoVO = new ResultUserInfoVO();
        resultUserInfoVO.setKaBaoUserDTO(kaBaoUserDTO);
        return ResultVOUtil.success(resultUserInfoVO);
    }

    @GetMapping("/innerinfo")
    public ResultVO innerGetUserInfo(@RequestParam("accessKey") String accessKey) {
        String token = AesUtil.decryptData(accessKey);
        KaBaoUserDTO kaBaoUserDTO = userService.findDTOByToken(token);
        kaBaoUserDTO.setToken(AesUtil.encryptData(kaBaoUserDTO.getToken()));
        ResultUserInfoVO resultUserInfoVO = new ResultUserInfoVO();
        resultUserInfoVO.setKaBaoUserDTO(kaBaoUserDTO);
        return ResultVOUtil.success(resultUserInfoVO);
    }

    @GetMapping("/test")
    public String test() {
        return "success!";
    }
}
